package org.deschutter.scans;

import org.deschutter.constants.Config;
import org.deschutter.exceptions.AddShipsToScanException;
import org.deschutter.scans.unit.Ship;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: Berten De Schutter
 * Date: 01-Jul-2009
 * Time: 11:27:21
 */
public class Unit extends Scan {

    public ArrayList<Ship> ships;

    public Unit(String ID, BigDecimal tick, String x, String y, String z, String scanpage, BigDecimal userID, Session session) {
        super(ID, Config.UNIT_SCAN, tick, x, y, z, scanpage, userID, session);
    }

    @Override
    protected String parseScan() {

        ships = new ArrayList<Ship>();
        Pattern compiledRegex;
        Matcher regexMatcher;


        // Get Ships
        compiledRegex = Pattern.compile("(\\w+\\s?\\w*\\s?\\w*)</td><td[^>]*>(\\d+)</td>");
        regexMatcher = compiledRegex.matcher(getScanpage().replace(",", ""));

        while (regexMatcher.find()) {
            Ship ship = new Ship(regexMatcher.group(1), new BigDecimal(regexMatcher.group(2)));
            ships.add(ship);
            //Queries.addShipToScan(ship.getName(),ship.getAmount(),getID());
        }

        try {
            addShipsToScan();
        } catch (AddShipsToScanException e) {
            System.out.println(e.getMistake());
        }
        return "Unit Scan on " + getX() + ":" + getY() + ":" + getZ() + " parsed successfuly";
    }

    public BigDecimal getTypeID() {
        return SCAN_TYPE_UNIT;
    }

    public void addShipsToScan() throws AddShipsToScanException {
        Transaction tx = null;
        org.deschutter.hibernate.Unit scan = null;
        tx = getSession().beginTransaction();
        for (Ship ship : ships) {
            try {

                scan = new org.deschutter.hibernate.Unit();

                scan.setScansByScanId(getHbscan());
                scan.setAmount(ship.getAmount().intValue());
                scan.setShipId(getShip(ship.getName()).getId().byteValue());
                String oi = getHbscan().getId() + ship.getName();
                scan.setId(oi.hashCode());
                getSession().saveOrUpdate(scan);

            } catch (Exception e) {
                if (tx != null) tx.rollback();
                System.out.println(e.getMessage());
                throw new AddShipsToScanException(e.getMessage(), getHbscan().getId(), ship.getName(), ship.getAmount());
            }
        }
        tx.commit();
    }

}
